package com.sskj.api.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sskj.api.domain.CommunicationProtocol;
import com.sskj.api.service.ICommunicationProtocolService;
import com.sskj.common.constant.RabbitMQConstant;
import com.sskj.common.dto.CommunicationProtocolDto;
import com.sskj.common.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ProtocolListener {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ICommunicationProtocolService communicationProtocolService;

    // 监听通信协议注册队列
    @RabbitListener(queues = RabbitMQConstant.DEVICE_PROTOCOL_REGISTER_QUEUE)
    public void iotData(String message) {
        log.info("消息内容: {}", message);
        if (StrUtil.isNotBlank(message)) {
            try {
                List<CommunicationProtocolDto> communicationProtocolDtoList = objectMapper.readValue(message, new TypeReference<List<CommunicationProtocolDto>>() {});

                List<CommunicationProtocol> communicationProtocols = getCommunicationProtocols(communicationProtocolDtoList);

                communicationProtocolService.batchAdd(communicationProtocols);
            } catch (JsonProcessingException e) {
                log.error("[通信协议注册]-反序列化异常。异常信息:{}|内容:{}", e.getMessage(), message);
            }
        }
    }

    @NotNull
    private static List<CommunicationProtocol> getCommunicationProtocols(List<CommunicationProtocolDto> communicationProtocolDtoList) {
        List<CommunicationProtocol> communicationProtocols = new ArrayList<>();
        if (communicationProtocolDtoList != null && !communicationProtocolDtoList.isEmpty()) {
            for (CommunicationProtocolDto protocolDto : communicationProtocolDtoList) {
                CommunicationProtocol communicationProtocol = new CommunicationProtocol();
                communicationProtocol.setName(protocolDto.getName());
                communicationProtocol.setCode(protocolDto.getCode());
                communicationProtocol.setDescription(protocolDto.getDescription());
                communicationProtocol.setStatus(1);

                communicationProtocols.add(communicationProtocol);
            }
        }
        return communicationProtocols;
    }
}
